<template>
  <el-dialog
    title="上传关键词"
    :visible.sync="show"
    :before-close="beforeClose">
    <div class="fileBox">
      <div
        v-if="fileName"
        class="file-wrap"
        @click="handleUpload">
        <div class="file-item">{{ fileName }}</div>
      </div>

      <el-button
        v-if="!fileName"
        @click="handleUpload"
        >点击选择文件</el-button
      >

      <input
        hidden
        ref="uploadKeyword"
        accept="text/plain"
        @change="onUploadChange($event)"
        type="file" />
    </div>
    <span class="tip">说明：关键词上传格式一行一个,支持txt格式。</span>
    <div
      class="dialog-footer"
      slot="footer">
      <el-button
        type="primary"
        :loading="btnLoading"
        @click="handleSubmit">
        确认上传
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { comeInKeyWordForm } from '@/api/sales'
export default {
  data() {
    return {
      fileName: '',
      show: false,
      btnLoading: false,
      keywordList: [],
    }
  },
  watch: {
    show(newVal) {
      if (!newVal) {
        this.fileName = null
      }
    },
  },
  props: {},
  methods: {
    beforeClose(done) {
      this.$refs.uploadKeyword.value = ''
      done()
    },

    handleUpload() {
      this.$refs.uploadKeyword.click()
    },

    onUploadChange(e) {
      // console.log(e)
      const file = e.target.files[0]
      this.fileName = file.name

      const reader = new FileReader()
      reader.readAsText(file, 'UTF-8')
      reader.onload = event => {
        const result = event.target.result || null
        if (result) {
          this.keywordList = result.split(/[(\r\n)\r\n]+/)
        }
      }
    },
    async handleSubmit() {
      if (!this.fileName) return this.$message.error('文件尚未上传成功')
      if (!this.keywordList.length) return this.$message.error('上传文件没有关键字')

      const keyWord = JSON.stringify(this.keywordList.join(','))

      this.btnLoading = true
      const data = await comeInKeyWordForm({ name_list: keyWord })

      if (data?.code === 0) {
        this.show = false
        this.btnLoading = false
        this.$emit('refresh')
      }
    },
  },
  mounted() {},
}
</script>

<style lang="scss" scoped>
.fileBox {
  padding-bottom: 10px;
}
.file-item {
  cursor: pointer;
  display: inline-block;
  // width: 200px;
  border: 1px solid #ccc;
  padding: 6px 20px;
  margin-bottom: 10px;
}
</style>
